from django.contrib.auth import authenticate, login
from django.contrib.auth.views import LoginView
from django.core import serializers
from django.core.handlers.base import logger
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import HttpResponseBadRequest, FileResponse, HttpResponse, JsonResponse
from django.shortcuts import render, redirect
# Create your views here.
from django.template.loader import render_to_string
from django.utils.functional import SimpleLazyObject
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import ListView, FormView
# from Lesson.forms import FileForm
from IM.models import AuthUser
from Lesson.forms import FileForm, UserForm
# from Lesson.models import FileInfo



# class UploadView(View):
#     def get(self, request):
#         return render(request, "upload.html", {"form": FileForm(),
#                                                "name": "miranda",
#                                                "file_size": 123443212,
#                                                "value": 12,
#                                                "html_tag": '<h1>this is my title</h1>'})
#
#     def post(self, request):
#         form = FileForm(request.POST, request.FILES)
#         if form.is_valid():
#             model = FileInfo()
#             model.title = form.cleaned_data['file'].name
#             model.file = form.cleaned_data['file']
#             model.save()
#             return redirect("download")
#         else:
#             return HttpResponseBadRequest()


# class DownloadView(View):
#     def get(self, request):
#         files = FileInfo.objects.all()
#         return render(request, "download.html", {'files': files})

@csrf_exempt
def user_view(request, *args, **kwargs):
    if request.method == "GET":
        return render(request, "slogin.html", {"form": UserForm()})


    elif request.method == "POST":
        user_form = UserForm(request.POST)
        if not user_form.is_valid():
            return HttpResponse("Invalid Form")

        user = authenticate(request,
                            username=user_form.cleaned_data['username'],
                            password=user_form.cleaned_data['password'])
        if user is None:
            return HttpResponse("Invalid username and password")
        login(request, user)
        return HttpResponse("Login Successfully")

class Users(View):
    def get(self, request):
        return render(request, "lesson_user.html", {"form": UserForm()})

        # users = AuthUser.objects.all()
        # return JsonResponse([model_to_dict(p, exclude=["avatar"]) for p in users], safe=False)
        # return JsonResponse([p.to_json() for p in users], safe=False)

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        try:
            logger.info("The request view is calling.")
        #TODO: 添加新用户
        except Exception as e:
            logger.exception(e)
        p = Paginator(None, 2)
        return HttpResponse()

class MyLoginView(LoginView):
    pass

    # form_class = UserForm
    # template_name = "slogin.html"

# class MyListView(View):
#     def get(self, request, *args, **kwargs):
#         model = getattr(self, "model")
#         template = getattr(self, "template_name")
#
#         object_list = model.objects.all()
#         return render(request, template, {"object_list": object_list})


# class FileInfoView(MyListView):
#     model = FileInfo
#     template_name = "download.html"


# class UserFormView(FormView):
#     template_name = 'lesson_user.html'
#     form_class = UserForm
#     success_url = "http://www.baidu.com"
#
#     def form_valid(self, form):
#         return super(UserFormView, self).form_valid(form)
#
# class User:
#     def __init__(self):
#         self.username = None
#         self.password = None
#
# u = User()
# u.username = "jim"
# u.password = "sfsdfdsfsdf"
#
# class MySerializer:
#     def dumps(self, data):
#         return "%s:%s" % (data.username, data.password)
#
#     def loads(self, data):
#         username, pwd = data.split(":")
#         u = User()
#         u.username = username
#         u.password = pwd
#
#         return u

class MyAuthenBackend:
    def authenticate(self, request, username, password):
        if username != 'jim':
            return None

        return AuthUser.objects.get(username='jim')


    def get_user(self, user_id):
        try:
            return AuthUser.objects.get(pk=user_id)
        except AuthUser.DoesNotExist:
            return None